package tech.yixiyun.framework.kuafu.controller;

import tech.yixiyun.framework.kuafu.component.ComponentResolveException;
import tech.yixiyun.framework.kuafu.kits.StringKit;

import java.util.Objects;

/**
 * @Controller注解value值的解析工具类
 */
public class PathResolver {

    /**
     * 解析
     * @param source 源字符串，一般就是Controller类的类名
     * @param pattern 解析规则，就是@Controller注解的value值
     * @return
     */
    public static String resolve(String source, String pattern) {
        String result = source;

        if (StringKit.isNotBlank(pattern)) {

            if (pattern.contains("(")) { //包含语法规则，就根据语法规则解析
                String[] patterns = StringKit.matchAll(pattern, "(?<=\\()[^)]+");
                for (String p : patterns) {
                    result = resolveByPattern(result, p );
                }
            } else {
                result = pattern;
            }
        }


        if (result.startsWith("/")) {
            result = result.substring(1);
        }
        if (result.endsWith("/")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 根据Controller注解的语法规则解析url
     * @param source 进行处理的源字符串
     * @param pattern //语法规则，详情看@Controller注解的 url属性 注释说明
     * @return
     */
    private static String resolveByPattern(String source, String pattern) {
        if (Objects.equals(pattern, "a")) { //首字母小写
            String firstLetter = source.substring(0, 1);
            return firstLetter.toLowerCase() + source.substring(1);
        }
        if (Objects.equals(pattern, "aa")) { //全部小写
            return source.toLowerCase();
        }
        if (Objects.equals(pattern, "AA")) { //全部转大写
            return source.toUpperCase();
        }
        if (pattern.startsWith("!")) { //去掉某个字符串
            if (pattern.length() == 1) {
                throw new ComponentResolveException("@Controller注解中配置的语法规则（"+ pattern +"）不正确，! 后需要有字符");
            }
            return source.replace(pattern.substring(1), "");
        }
        if (pattern.contains("~")) {//替换字符
            String[] strs = pattern.split("~");
            if (strs.length != 2 || StringKit.isBlank(strs[0])) {
                throw new ComponentResolveException("@Controller注解中配置的语法规则（"+ pattern +"）不正确，~ 前后需要有字符");
            }
            return source.replace(strs[0], strs[1]);
        }
        if (pattern.contains("+")) { //前后拼接字符串
            if (pattern.length() == 1) {
                throw new ComponentResolveException("@Controller注解中配置的语法规则（"+ pattern +"）不正确，+ 前或后需要有字符");
            }
            //前后都拼
            String[] strs = pattern.split("\\+");
            if (strs.length == 1) { // aaaaa+
                return strs[0] + source;
            }
            // +aaa 或者 aaa+bbb
            return strs[0] + source + strs[1];
        }
        return source;
    }


}
